#ifndef BufferedServerIoThread_H
#define BufferedServerIoThread_H

#include "model-server/ServerIoThread.h"

#include <QtCore>

using namespace simodo::edit::plugin::model_server;

struct ProcessSettings
{
    std::string              process_path;
    std::vector<std::string> process_args;
};

class BufferedServerIoThread : public QObject
{
public:
    // 1 / 60Hz = 0.01(6)s
    static constexpr int DEFAULT_TIMER_INTERVAL = 1000 / 20;
    static constexpr int DEFAULT_BUFFER_SIZE = 2000;

    BufferedServerIoThread( ProcessSettings
                          , int timer_interval = DEFAULT_TIMER_INTERVAL
                          , int buffer_size = DEFAULT_BUFFER_SIZE
                          );
    ~BufferedServerIoThread();

    ServerIoService & service()
    {
        return _thread.service();
    }

    void start();
    bool isRunning();
    void stop();
    void clearBuffer();

    void timerEvent(QTimerEvent * event) override;

signals:
    void doStart();
    void doStop();
    void recieved(QVector<QJsonObject> message);

private:
    Q_OBJECT

    ServerIoThread _thread;
    int _buffer_size;
    QQueue<QJsonObject> _buffer;
    QMutex _buffer_mutex;

    int  _timer_id;
    int  _timer_interval;
    long _timer_start_time;

    void _emit_recieved();

    void _startTimer();
    void _stopTimer();

private slots:
    void _start();
    void _stop();
    void _recieved(QVariant message);
};

#endif // BufferedServerIoThread_H